/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.ListPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;
import android.util.Log;
import com.android.settings.R;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.lang.Integer;

public class PowerOnRepeatPreference extends ListPreference {

    // Initial value that can be set with the values saved in the database.
    private DaysOfWeek mDaysOfWeek = new DaysOfWeek(0);
    // New value that will be set if a positive result comes back from the
    // dialog.
    private DaysOfWeek mNewDaysOfWeek = new DaysOfWeek(0);
    
    final Context mContext;
    private boolean mShowMondayToSunday=false;
    
    String[] values =null;

	public PowerOnRepeatPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mShowMondayToSunday = true;
		
			
		//setEntries(R.array.timer_repeat_entries);
		//setEntryValues(R.array.timer_repeat_values);
		 String[] weekdays = new DateFormatSymbols().getWeekdays();
		 values = new String[] {
		 	this.getContext().getResources().getString(R.string.use_on_time),
			this.getContext().getResources().getString(R.string.once),
			        weekdays[Calendar.MONDAY],
			        weekdays[Calendar.TUESDAY],
			        weekdays[Calendar.WEDNESDAY],
			        weekdays[Calendar.THURSDAY],
			        weekdays[Calendar.FRIDAY],
			        weekdays[Calendar.SATURDAY],
			        weekdays[Calendar.SUNDAY]
			    };
		 //setEntries(values);
		 //setEntryValues(values);
		setEntries(R.array.timer_repeat_entries);
		setEntryValues(R.array.timer_repeat_values);
		
	}

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        if (positiveResult) {
            mDaysOfWeek.set(mNewDaysOfWeek);
            setSummary(mDaysOfWeek.toString(getContext(), true));
            callChangeListener(mDaysOfWeek);
        }
        
        //restore init repeat list
        if(mShowMondayToSunday){
        	mShowMondayToSunday=true;
        	setEntries(R.array.timer_repeat_entries);
    		setEntryValues(R.array.timer_repeat_values);
        }
    }
    
    
    private boolean[] getDaysOfWeekBooleanArray(DaysOfWeek daysOfWeek)
    {

    	boolean[] initArray =daysOfWeek.getBooleanArray();
    	boolean[] result = new boolean[initArray.length+1];
    	for(int i=0;i<initArray.length;i++){
    		result[i] =initArray[i];
    	}
    	result[result.length-1]=false;
    
    	return result;
    }

    private int getSelectedRepeat(DaysOfWeek daysOfWeek){
    	String[]  valuesArr = mContext.getResources().getStringArray(R.array.timer_repeat_values);
    	for(int i=0;i<valuesArr.length;i++){
    		int valueInt =Integer.parseInt(valuesArr[i]);
    		if(valueInt==daysOfWeek.getCoded()){
    			return i;
    		}
    	}
    	return 0;
    	
    }
    
	@Override
	protected void onPrepareDialogBuilder(Builder builder) {

		final CharSequence[] entries = getEntries();
		final CharSequence[] entryValues = getEntryValues();
		
		if (mShowMondayToSunday) {
			builder.setMultiChoiceItems(entries, getDaysOfWeekBooleanArray(mDaysOfWeek),
					new DialogInterface.OnMultiChoiceClickListener() {
						public void onClick(DialogInterface dialog, int which,
								boolean isChecked) {
									Log.d("dialog",  "entryValue" + entryValues[0]);	
							if(isChecked)
							{
								if(entryValues[0].equals(String.valueOf(which)))
								{
									Log.d("dialog",  "entryValue eq 0");	
									for(int i = 1; i < entryValues.length-4; i++)
									((View)(((AlertDialog)dialog).getListView().getChildAt(which+i))).setEnabled(true);
								}
								if(entryValues[1].equals(String.valueOf(which)))
								{
									Log.d("dialog",  "entryValue eq 0");	
									for(int i = 1; i < entryValues.length-4; i++)
									((View)(((AlertDialog)dialog).getListView().getChildAt(which+i))).setEnabled(false);
								}
								
							}
							else
							{
								//if(Integer.parseInt((String)entryValues[0]) == which)
								if(entryValues[0].equals(String.valueOf(which)))
								{
									Log.d("dialog",  "entryValue eq 0");
									for(int i = 1; i < entryValues.length-4; i++)
									((View)(((AlertDialog)dialog).getListView().getChildAt(which+i))).setEnabled(false);
								}
								if(entryValues[1].equals(String.valueOf(which)))
								{
									Log.d("dialog",  "entryValue eq 0");
									for(int i = 1; i < entryValues.length-4; i++)
									((View)(((AlertDialog)dialog).getListView().getChildAt(which+i))).setEnabled(true);
								}
							}
							mNewDaysOfWeek.set(which, isChecked);
						}
					});
		}
		else 
		{     //!mShowMondayToSunday
			builder.setSingleChoiceItems(entries, getSelectedRepeat(mDaysOfWeek),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (which == (entryValues.length - 1)) {
								((AlertDialog) dialog).dismiss();
								mShowMondayToSunday = true;
								setEntries(values);
								setEntryValues(values);
								PowerOnRepeatPreference.this.showDialog(null);
							} else {
								mNewDaysOfWeek.set(Integer
										.parseInt(entryValues[which].toString()));
							}
						}
					});
		}// else end

	}

    public void setDaysOfWeek(DaysOfWeek dow) {
        mDaysOfWeek.set(dow);
        mNewDaysOfWeek.set(dow);
        setSummary(dow.toString(getContext(), true));
    }

    public DaysOfWeek getDaysOfWeek() {
        return mDaysOfWeek;
    }

    static final class DaysOfWeek {

    private static int[] DAY_MAP = new int[] {
        Calendar.MONDAY,
        Calendar.TUESDAY,
        Calendar.WEDNESDAY,
        Calendar.THURSDAY,
        Calendar.FRIDAY,
        Calendar.SATURDAY,
        Calendar.SUNDAY,
    };

    // Bitmask of all repeating days
    private int mDays;

    DaysOfWeek(int days) {
        mDays = days;
    }

    public String toString(Context context, boolean showNever) {
        StringBuilder ret = new StringBuilder();

        // no days
        if (mDays == 0) {
            return showNever ?
                    context.getText(R.string.never).toString() : "";
        }

        // every day
        if (mDays == 0x7f) {
            return context.getText(R.string.every_day).toString();
        }

        // count selected days
        int dayCount = 0, days = mDays;
        while (days > 0) {
            if ((days & 1) == 1) dayCount++;
            days >>= 1;
        }

        // short or long form?
        DateFormatSymbols dfs = new DateFormatSymbols();
        String[] dayList = (dayCount > 1) ?
                dfs.getShortWeekdays() :
                dfs.getWeekdays();

        // selected days
        for (int i = 0; i < 7; i++) {
            if ((mDays & (1 << i)) != 0) {
                ret.append(dayList[DAY_MAP[i]]);
                dayCount -= 1;
                if (dayCount > 0) ret.append(
                        context.getText(R.string.day_concat));
            }
        }
        return ret.toString();
    }

    private boolean isSet(int day) {
        return ((mDays & (1 << day)) > 0);
    }

    public void set(int day, boolean set) {
        if (set) {
            mDays |= (1 << day);
        } else {
            mDays &= ~(1 << day);
        }
    }

    public void set(DaysOfWeek dow) {
        mDays = dow.mDays;
    }

// wangdanyang add
    public void set(int days) {
        mDays = days;
    }

    public int getCoded() {
        return mDays;
    }

    // Returns days of week encoded in an array of booleans.
    public boolean[] getBooleanArray() {
        boolean[] ret = new boolean[9];
        for (int i = 0; i < 9; i++) {
            ret[i] = isSet(i);
        }
        return ret;
    }

    public boolean isRepeatSet() {
        return mDays != 0;
    }

    /**
     * returns number of days from today until next alarm
     * @param c must be set to today
     */
    public int getNextAlarm(Calendar c) {
        if (mDays == 0) {
            return -1;
        }

        int today = (c.get(Calendar.DAY_OF_WEEK) + 5) % 7;

        int day = 0;
        int dayCount = 0;
        for (; dayCount < 7; dayCount++) {
            day = (today + dayCount) % 7;
            if (isSet(day)) {
                break;
            }
        }
        return dayCount;
    }
}
}
